package action;

import beans.ClassroomFacadeLocal;
import beans.JmsActionFacadeLocal;
import beans.PersonToClassFacadeLocal;
import beans.UserFacadeLocal;
import com.opensymphony.xwork2.ActionSupport;
import components.Buttons;
import components.ProffessorButtonGroup;
import components.StudentButtonGroup;
import entities.Class;
import entities.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJBException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import services.PageDetails;

/**
 *
 * @author corneliugosa
 */
public class LoginAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {
    ClassroomFacadeLocal classroomFacade = lookupClassroomFacadeLocal();
    JmsActionFacadeLocal jmsActionFacade = lookupJmsActionFacadeLocal();
    PersonToClassFacadeLocal personToClassFacade = lookupPersonToClassFacadeLocal();
    UserFacadeLocal userFacade = lookupUserFacadeLocal();
    
    private List<Classroom> classroomList;
    private String username;
    private String pass;
    private String message;
    private String errorMessage;
    private User user = null;
    private PageDetails pageDetails;
    private entities.Class cls;
    private HttpServletRequest request;
    private HttpServletResponse response;
    private Buttons buttons;

    public void validate() {
        if (getUsername().length() == 0) {
            addFieldError("username", "User Name is required");
        }

        if (getPass().length() == 0) {
            addFieldError("pass", getText("password.required"));
        }
    }

    public String execute() {
        HttpSession session = request.getSession();
        
        try {
            user = userFacade.findByNameAndPass(username, pass);
        } catch (EJBException e) {
//            e.printStackTrace();
            message = "Incorrect username or password!";
            return "failure";
        }

//        new Thread() {
//
//            public void run() {
//                while (true) {
//                    try {
//                        Thread.sleep(3000);
//                        
//                        JmsAction act = jmsActionFacade.examRequest(100);
//                        if (act != null && user.getRole().getId() == 3) {
//                            System.out.println("exam scheduled in thread!");
//                            errorMessage = "exam scheduled!";
//                            session.setAttribute("serviciu", act);
//                            jmsActionFacade.remove(act);
//                        }
//                        
//                    } catch (InterruptedException ex) {
//                        Logger.getLogger(LoginAction.class.getName()).log(Level.SEVERE, null, ex);
//                    }
//                }
//            }
//        }.start();

        if (user != null) {       
            pageDetails = new PageDetails();

            switch (user.getRole().getId()) {
                case 1: {
                    buttons = new StudentButtonGroup();
                    pageDetails.setPageTitle("Student's personal page");
                    pageDetails.setButtonPageDisplay("home");

                    cls = user.getPerson().getClasses().get(0);
                    session.setAttribute("buttonList", buttons.getButtonList1());
                    session.setAttribute("class", cls);
                }
                break;

                case 2: {
                    List<Person> personList = new ArrayList<Person>();
                    List<SubjectMatter> smList = new ArrayList<SubjectMatter>();
                    smList.add(new SubjectMatter());
                    
                    List<entities.Class> classes = user.getPerson().getClasses();
                    Set<SubjectMatter> subjects = user.getPerson().getSubjectMatterList();
                    buttons = new ProffessorButtonGroup();
                    pageDetails.setPageTitle("Proffessor's personal page");
                    pageDetails.setButtonPageDisplay("homeP");
                    session.setAttribute("smList", smList);
                    session.setAttribute("buttonList", buttons.getButtonList1());
                    session.setAttribute("classes", classes);
                    session.setAttribute("personList", personList);
                    session.setAttribute("subjects-to-teach", subjects);
                }
                break;

                case 3: {
                    pageDetails.setPageTitle("Secretary's personal page");
                    pageDetails.setButtonPageDisplay("homeS");
                }
                break;
            }

            classroomList = classroomFacade.findAll(); 
            session.setAttribute("classroomList", classroomList);
            session.setAttribute("logged", "yes");
            session.setAttribute("pageDetails", pageDetails);
            session.setAttribute("user", user);
            return SUCCESS;
        }

        return "failure";
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public UserFacadeLocal getUserFacade() {
        return userFacade;
    }

    public void setUserFacade(UserFacadeLocal userFacade) {
        this.userFacade = userFacade;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Buttons getButtons() {
        return buttons;
    }

    public void setButtons(Buttons buttons) {
        this.buttons = buttons;
    }

    public PageDetails getPageDetails() {
        return pageDetails;
    }

    public void setPageDetails(PageDetails pageDetails) {
        this.pageDetails = pageDetails;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    public Class getCls() {
        return cls;
    }

    public void setCls(Class cls) {
        this.cls = cls;
    }

    private UserFacadeLocal lookupUserFacadeLocal() {
        try {
            Context c = new InitialContext();
            return (UserFacadeLocal) c.lookup("java:global/School/School-ejb/UserFacade!beans.UserFacadeLocal");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    private PersonToClassFacadeLocal lookupPersonToClassFacadeLocal() {
        try {
            Context c = new InitialContext();
            return (PersonToClassFacadeLocal) c.lookup("java:global/School/School-ejb/PersonToClassFacade!beans.PersonToClassFacadeLocal");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
    
    

    private JmsActionFacadeLocal lookupJmsActionFacadeLocal() {
        try {
            Context c = new InitialContext();
            return (JmsActionFacadeLocal) c.lookup("java:global/School/School-ejb/JmsActionFacade!beans.JmsActionFacadeLocal");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.response = response;
    }
    
    public JmsActionFacadeLocal getJmsActionFacade() {
        return jmsActionFacade;
    }

    public void setJmsActionFacade(JmsActionFacadeLocal jmsActionFacade) {
        this.jmsActionFacade = jmsActionFacade;
    }

    public PersonToClassFacadeLocal getPersonToClassFacade() {
        return personToClassFacade;
    }

    public void setPersonToClassFacade(PersonToClassFacadeLocal personToClassFacade) {
        this.personToClassFacade = personToClassFacade;
    }
    
    public List<Classroom> getClassroomList() {
        return classroomList;
    }

    public void setClassroomList(List<Classroom> classroomList) {
        this.classroomList = classroomList;
    }

    private ClassroomFacadeLocal lookupClassroomFacadeLocal() {
        try {
            Context c = new InitialContext();
            return (ClassroomFacadeLocal) c.lookup("java:global/School/School-ejb/ClassroomFacade!beans.ClassroomFacadeLocal");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}
